package com.sqx.modules.tbOrders.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.address.dao.AddressDao;
import com.sqx.modules.address.entity.Address;
import com.sqx.modules.app.dao.SysEvaluateDao;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.SysEvaluate;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.brand.dao.BrandDao;
import com.sqx.modules.brand.entity.Brand;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.goods.dao.GoodsDao;
import com.sqx.modules.goods.dao.GoodsSkuDao;
import com.sqx.modules.goods.entity.Goods;
import com.sqx.modules.goods.entity.GoodsAndSku;
import com.sqx.modules.goods.service.GoodsAndSkuService;
import com.sqx.modules.goods.service.GoodsService;
import com.sqx.modules.goodsType.dao.GoodsTypeDao;
import com.sqx.modules.goodsType.entity.GoodsType;
import com.sqx.modules.labelType.dao.LabelTypeDao;
import com.sqx.modules.labelType.entity.LabelType;
import com.sqx.modules.message.dao.MessageInfoDao;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.pay.dao.PayDetailsDao;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.pay.service.AliPayService;
import com.sqx.modules.pay.service.WxService;
import com.sqx.modules.recovery.dao.GoodsRecoveryDao;
import com.sqx.modules.recovery.dao.GoodsSpecificationsDao;
import com.sqx.modules.recovery.entity.AttributeValue;
import com.sqx.modules.recovery.entity.GoodsRecovery;
import com.sqx.modules.recovery.entity.GoodsSpecifications;
import com.sqx.modules.search.service.SearchRecordService;
import com.sqx.modules.stockManage.dao.StockManageDao;
import com.sqx.modules.stockManage.entity.StockManage;
import com.sqx.modules.tbCoupon.entity.TbCouponUser;
import com.sqx.modules.tbCoupon.service.TbCouponUserService;
import com.sqx.modules.tbOrders.dao.TbOrdersDao;
import com.sqx.modules.tbOrders.entity.TbOrders;
import com.sqx.modules.tbOrders.entity.vo.TbOrdersVO;
import com.sqx.modules.tbOrders.service.TbOrdersService;
import com.sqx.modules.trendsComment.dao.TrendsCommentDao;
import com.sqx.modules.trendsComment.entity.TrendsComment;
import com.sqx.modules.trendsComment.service.ITrendsCommentService;
import com.sqx.modules.trendsComment.vo.TrendsCommentVo;
import com.sqx.modules.userCertification.dao.UserCertificationDao;
import com.sqx.modules.userCertification.entity.UserCertification;
import com.sqx.modules.utils.BaiDuUtils;
import com.sqx.modules.utils.SenInfoCheckUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Admin
 * @description 针对表【tb_orders(商品订单)】的数据库操作Service实现
 * @createDate 2024-07-09 11:09:26
 */
@Service
public class TbOrdersServiceImpl extends ServiceImpl<TbOrdersDao, TbOrders> implements TbOrdersService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private TbCouponUserService couponUserService;

    @Autowired
    private UserCertificationDao userCertificationDao;

    @Autowired
    private UserMoneyService userMoneyService;

    @Autowired
    private WxService wxService;

    @Autowired
    private AliPayService aliPayService;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private SysEvaluateDao sysEvaluateDao;
    @Autowired
    private GoodsSkuDao goodsSkuDao;

    @Autowired
    private GoodsSpecificationsDao goodsSpecificationsDao;

    @Autowired
    private GoodsRecoveryDao goodsRecoveryDao;
    @Autowired
    private GoodsAndSkuService goodsAndSkuService;
    @Autowired
    private AddressDao addressDao;
    @Autowired
    private UserService userService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private PayDetailsDao payDetailsDao;

    @Autowired
    private LabelTypeDao labelTypeDao;

    @Autowired
    private GoodsTypeDao goodsTypeDao;
    @Autowired
    private BrandDao brandDao;
    @Autowired
    private SearchRecordService searchRecordService;
    @Autowired
    private MessageInfoDao messageInfoDao;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ITrendsCommentService trendsCommentService;
    @Autowired
    private TrendsCommentDao trendsCommentDao;
    @Autowired
    private StockManageDao stockManageDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result placeOrder(TbOrders tbOrders) {
        String platform = commonInfoService.findOne(448).getValue();
        BigDecimal platePrice = new BigDecimal(platform);
        if (tbOrders.getRetrieveType() == 0) {
            UserEntity user = userDao.selectById(tbOrders.getSellerId());
            if (user == null) {
                return Result.error("用户不存在,请重新登录");
            }
//            UserCertification userCertification = userCertificationDao.selectOne(new LambdaQueryWrapper<UserCertification>()
//                    .eq(UserCertification::getUserId, user.getUserId()));
//            if (userCertification != null) {
//                if (userCertification.getStatus() != 1) {
//                    return Result.error("请先实名认证");
//                }
//            } else {
//                return Result.error("请先实名认证");
//            }
            Goods goods = goodsDao.selectById(tbOrders.getGoodId());
            if (goods == null) {
                return Result.error("商品信息不存在");
            }
            goods.setIsStock(2);
            if (tbOrders.getBuyNum() != null) {
                goods.setStock(tbOrders.getBuyNum());
            } else {
                goods.setStock(1);
            }
            // 如果是回收订单，查询商品规格,并拿到价格相加，设定回收商品的回收价格
            if (tbOrders.getOrderMoney() != null && (goods.getFreeMoney() == null || goods.getFreeMoney().compareTo(BigDecimal.ZERO) == 0)) {
                goods.setGoodPrice(tbOrders.getOrderMoney());
                goods.setReceivedPrice(tbOrders.getOrderMoney());
                tbOrders.setTotalPrice(tbOrders.getOrderMoney());
            } else if (goods.getFreeMoney() != null && tbOrders.getOrderMoney() != null) {
                goods.setGoodPrice(tbOrders.getOrderMoney());
                goods.setReceivedPrice(tbOrders.getOrderMoney().add(goods.getFreeMoney()));
                tbOrders.setTotalPrice(tbOrders.getOrderMoney().add(goods.getFreeMoney()));
            }
            goodsDao.updateById(goods);
            tbOrders.setRecycledStatus(2);
            tbOrders.setIsPay(0);
            tbOrders.setStatus(6);
            tbOrders.setOrderNumber(generateOrder());
            tbOrders.setCreateTime(new Date());
            if (goods.getRecoveryId() != null) {
                tbOrders.setRecoveryId(goods.getRecoveryId());
            }
            Address address = addressDao.selectById(tbOrders.getAddressId());
            if (address != null) {
                tbOrders.setAddressDetail(address.getProvince() + address.getCity() + address.getDistrict() + address.getAddressDetail());
            }
            tbOrders.setDeliveryStatus(tbOrders.getDeliveryStatus());
            int count = baseMapper.insert(tbOrders);
            if (count <= 0) {
                return Result.error("下单失败");
            }
            return Result.success().put("data", tbOrders.getOrderId().toString());
        } else {
            UserEntity user = userDao.selectById(tbOrders.getBuyerId());
            if (user == null) {
                return Result.error("用户不存在,请重新登录");
            }
//            UserCertification userCertification = userCertificationDao.selectOne(new LambdaQueryWrapper<UserCertification>()
//                    .eq(UserCertification::getUserId, user.getUserId()));
//            if (userCertification != null) {
//                if (userCertification.getStatus() != 1) {
//                    return Result.error("请先实名认证");
//                }
//            } else {
//                return Result.error("请先实名认证");
//            }
            Goods goods = goodsDao.selectById(tbOrders.getGoodId());
            if (goods == null) {
                return Result.error("商品信息不存在");
            }
            if (goods.getIsEnable() == 0 || goods.getStatus() != 1) {
                return Result.error("该商品状态有误或已下架，请检查！");
            }
            BigDecimal goodPrice = goods.getGoodPrice().multiply(new BigDecimal(tbOrders.getBuyNum()));
            tbOrders.setOrderMoney(goodPrice);
            if (goods.getFreeMoney() != null) {
                tbOrders.setOrderMoney(goods.getGoodPrice().add(goods.getFreeMoney()));
            } else {
                tbOrders.setOrderMoney(goods.getGoodPrice().multiply(new BigDecimal(tbOrders.getBuyNum())));
            }
            if (tbOrders.getFirstCommission() == null) {
                tbOrders.setFirstCommission(BigDecimal.ZERO);
            }
            if (tbOrders.getSecondCommission() == null) {
                tbOrders.setSecondCommission(BigDecimal.ZERO);
            }
            tbOrders.setTotalPrice(tbOrders.getOrderMoney());
            if (tbOrders.getPlatformIncome() == null) {
                tbOrders.setPlatformIncome(BigDecimal.ZERO);
            }
            // 这里的优惠券id是客户领取的优惠券表的id
            if (tbOrders.getCouponId() != null) {
                TbCouponUser tbCouponUser = couponUserService.getById(tbOrders.getCouponId());
                if (tbCouponUser == null) {
                    return Result.error("未持有当前优惠券");
                }
                if (tbCouponUser.getStatus() == 1) {
                    return Result.error("当前优惠券已使用");
                }
                if (tbCouponUser.getStatus() == 2) {
                    return Result.error("当前优惠券已失效");
                }
                //如果订单金额大于优惠券最小订单金额
                if (tbOrders.getTotalPrice().compareTo(tbCouponUser.getMinMoney()) >= 0) {
                    tbOrders.setTotalPrice(tbOrders.getTotalPrice().subtract(tbCouponUser.getMoney()));
                    tbOrders.setPlatformIncome(tbOrders.getTotalPrice().multiply(platePrice));
                    tbOrders.setSellerIncome(tbOrders.getTotalPrice().subtract(tbOrders.getPlatformIncome()));
                    tbCouponUser.setStatus(1);
                    tbCouponUser.setCouponId(tbCouponUser.getId());
                    tbOrders.setCouponMoney(tbCouponUser.getMoney());
                    couponUserService.updateById(tbCouponUser);
                } else {
                    return Result.error("订单金额不满足最低满减金额");
                }
            } else {
                tbOrders.setTotalPrice(tbOrders.getOrderMoney());
                tbOrders.setPlatformIncome(tbOrders.getTotalPrice().multiply(platePrice));
                tbOrders.setSellerIncome(tbOrders.getTotalPrice().subtract(tbOrders.getPlatformIncome()));
            }
            if (goods.getIsStock() != null && goods.getIsStock() == 2) {
                if (!goodsService.selectStockByGoodId(goods.getGoodId(), tbOrders.getBuyNum())) {
                    return Result.error("库存不足，请联系发布人！");
                }
            }
            Address address = addressDao.selectById(tbOrders.getAddressId());
            if (address != null) {
                tbOrders.setAddressDetail(address.getProvince() + address.getCity() + address.getDistrict() + address.getAddressDetail());
            }
            tbOrders.setDeliveryStatus(goods.getDelivery());
            tbOrders.setIsPay(0);
            tbOrders.setStatus(0);
            tbOrders.setOrderNumber(generateOrder());
            if (goods.getRecoveryId() != null) {
                tbOrders.setRecoveryId(goods.getRecoveryId());
            }
            tbOrders.setCreateTime(new Date());
            if (tbOrders.getBuyerId().equals(tbOrders.getSellerId())) {
                return Result.error("不能购买自己发布的商品");
            }
            tbOrders.setSellerId(goods.getUserId());
            tbOrders.setBuyerId(user.getUserId());
            if (goods.getStockId() != null) {
                StockManage stockManage = stockManageDao.selectById(goods.getStockId());
                if (stockManage != null) {
                    if (stockManage.getStock() < tbOrders.getBuyNum()) {
                        return Result.error("回收管理库存不足，请联系管理员！");
                    }
                }
            }
            int count = baseMapper.insert(tbOrders);
            if (count <= 0) {
                return Result.error("下单失败");
            } else {
                if (goods.getStockId() != null) {
                    StockManage stockManage = stockManageDao.selectById(goods.getStockId());
                    if (stockManage != null) {
//                        stockManage.setStock(stockManage.getStock() - tbOrders.getBuyNum());
//                        stockManage.setOutStock(stockManage.getOutStock() + tbOrders.getBuyNum());
//                        stockManageDao.updateById(stockManage);
                        goods.setStock(goods.getStock() - tbOrders.getBuyNum());
                        goodsService.updateByStock(goods);
                    }
                }
                if (goods.getIsStock() != null && goods.getIsStock() == 2) {
                    goodsService.updateStockByGoodId(goods.getGoodId(), tbOrders.getBuyNum());
                }
            }
            return Result.success().put("data", tbOrders.getOrderId().toString());
        }
    }

    private String generateOrder() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = sdf.format(new Date());
        int i = (int) ((Math.random() * 9 + 1) * 10000);
        return format + i;
    }

    @Override
    public Result getAppTbOrdersList(Integer page, Integer limit, TbOrders tbOrders) {
        UserEntity user = userDao.selectById(tbOrders.getBuyerId());
        if (user == null) {
            return Result.error("用户信息不存在,请重新登录");
        }
        Page<TbOrders> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        IPage<TbOrders> ordersVoIPage = baseMapper.getAppTbOrdersList(pages, tbOrders);
        for (TbOrders record : ordersVoIPage.getRecords()) {
            Goods goods = goodsDao.selectById(record.getGoodId());
            record.setGoods(goods);
            //查询商品规格信息关联信息
            List<GoodsAndSku> goodsAndSkus = goodsAndSkuService.getBaseMapper().selectList(new QueryWrapper<GoodsAndSku>()
                    .eq("goods_id", record.getGoodId()));
            //解析规格信息
            List<GoodsSpecifications> specificationsList = new ArrayList<>();
            if (goodsAndSkus != null) {
                for (GoodsAndSku goodsAndSku : goodsAndSkus) {
                    GoodsSpecifications goodsSpecifications = goodsSpecificationsDao.selectById(goodsAndSku.getSkuId());
                    if (goodsSpecifications != null) {
                        String attributeValues = goodsSpecifications.getAttributeValue();
                        // 使用正则表达式修正字符串中的单引号为双引号
                        attributeValues = attributeValues.replaceAll("'", "\"");
                        // 使用正则表达式将等号替换为冒号
                        attributeValues = attributeValues.replaceAll("(?<=[a-zA-Z0-9_])=", ":");
                        List<AttributeValue> attributeValuesList = JSON.parseArray(attributeValues, AttributeValue.class);
                        goodsSpecifications.setAttributes(attributeValuesList);
                        // 解析 sku_value 字段得到一组 attribute_value 的 ID
                        String[] attributeValueIds = StringUtils.split(goodsAndSku.getSkuValue(), ',');
                        List<AttributeValue> filteredAttributes = new ArrayList<>();
                        for (AttributeValue attribute : goodsSpecifications.getAttributes()) {
                            if (attributeValueIds != null && Arrays.asList(attributeValueIds).contains(String.valueOf(attribute.getId()))) {
                                attribute.setSpecId(String.valueOf(goodsSpecifications.getId()));
                                filteredAttributes.add(attribute);
                            }
                        }
                        if (goods.getGoodStatus() == 1) {
                            // 将所有商品规格价格相加，存入这个字段
                            BigDecimal totalPrice = filteredAttributes.stream()
                                    .map(attr -> new BigDecimal(attr.getAttPrice()))
                                    .reduce(BigDecimal.ZERO, BigDecimal::add);
                            tbOrders.setGoodPrice(totalPrice);
                        }
                        // 设置过滤后的属性值列表
                        goodsSpecifications.setAttributes(filteredAttributes);
                        // 添加到最终的规格列表中
                        specificationsList.add(goodsSpecifications);
                    }
                }
                // 将规格信息添加到 GoodsVo 中
                tbOrders.setSpecifications(specificationsList);
            }
        }
        return Result.success().put("data", ordersVoIPage);
    }

    @Override
    public Result getAppOrdersDetail(Long orderId, Long userId) {
        UserEntity user = userDao.selectById(userId);
        if (user == null) {
            return Result.error("用户信息不存在,请重新登录");
        }
        TbOrders tbOrdersVO = baseMapper.getAppOrdersDetail(orderId, userId);
        if (tbOrdersVO == null) {
            return Result.error("订单信息不存在");
        }
        UserEntity seller = userDao.selectById(tbOrdersVO.getSellerId());
        if (seller != null) {
            tbOrdersVO.setSellerName(seller.getUserName());
            tbOrdersVO.setSellerPhone(seller.getPhone());
        }
        UserEntity buyer = userDao.selectById(tbOrdersVO.getBuyerId());
        if (buyer != null) {
            tbOrdersVO.setBuyerName(buyer.getUserName());
        }
//        Address address = addressDao.selectById(tbOrdersVO.getAddressId());
//        if (address != null) {
//            tbOrdersVO.setAddressDetail(address.getAddressDetail());
//        }
        Goods goods = goodsDao.selectById(tbOrdersVO.getGoodId());
        if (goods != null) {
            Brand brand = brandDao.selectById(goods.getBrandId());
            if (brand != null) {
                tbOrdersVO.setBrandName(brand.getBrandName());
                tbOrdersVO.setBrandImg(brand.getImg());
            }
            LabelType labelType = labelTypeDao.selectById(goods.getLabelId());
            if (labelType != null) {
                tbOrdersVO.setLabel(labelType.getLabel());
            }
            GoodsRecovery goodsRecovery = goodsRecoveryDao.selectById(tbOrdersVO.getRecoveryId());
            if (goodsRecovery != null) {
                tbOrdersVO.setRecoveryName(goodsRecovery.getName());
            }
        }
        //查询商品规格信息关联信息
        List<GoodsAndSku> goodsAndSkus = goodsAndSkuService.getBaseMapper().selectList(new QueryWrapper<GoodsAndSku>()
                .eq("goods_id", tbOrdersVO.getGoodId()));
        //解析规格信息
        List<GoodsSpecifications> specificationsList = new ArrayList<>();
        if (goodsAndSkus != null) {
            for (GoodsAndSku goodsAndSku : goodsAndSkus) {
                GoodsSpecifications goodsSpecifications = goodsSpecificationsDao.selectById(goodsAndSku.getSkuId());
                if (goodsSpecifications != null) {
                    String attributeValues = goodsSpecifications.getAttributeValue();
                    // 使用正则表达式修正字符串中的单引号为双引号
                    attributeValues = attributeValues.replaceAll("'", "\"");
                    // 使用正则表达式将等号替换为冒号
                    attributeValues = attributeValues.replaceAll("(?<=[a-zA-Z0-9_])=", ":");
                    List<AttributeValue> attributeValuesList = JSON.parseArray(attributeValues, AttributeValue.class);
                    goodsSpecifications.setAttributes(attributeValuesList);
                    // 解析 sku_value 字段得到一组 attribute_value 的 ID
                    String[] attributeValueIds = StringUtils.split(goodsAndSku.getSkuValue(), ',');
                    List<AttributeValue> filteredAttributes = new ArrayList<>();
                    for (AttributeValue attribute : goodsSpecifications.getAttributes()) {
                        if (attributeValueIds != null && Arrays.asList(attributeValueIds).contains(String.valueOf(attribute.getId()))) {
                            attribute.setSpecId(String.valueOf(goodsSpecifications.getId()));
                            filteredAttributes.add(attribute);
                        }
                    }
                    Goods good = goodsDao.selectById(tbOrdersVO.getGoodId());
                    if (good != null) {
                        // 将所有商品规格价格相加，存入这个字段
                        if (good.getGoodStatus() == 1) {
                            // 将所有商品规格价格相加，存入这个字段
                            BigDecimal totalPrice = filteredAttributes.stream()
                                    .map(attr -> new BigDecimal(attr.getAttPrice()))
                                    .reduce(BigDecimal.ZERO, BigDecimal::add);
                            tbOrdersVO.setGoodPrice(totalPrice);
                        }
                    }
                    // 设置过滤后的属性值列表
                    goodsSpecifications.setAttributes(filteredAttributes);
                    // 添加到最终的规格列表中
                    specificationsList.add(goodsSpecifications);
                }
            }
            // 将规格信息添加到 GoodsVo 中
            tbOrdersVO.setSpecifications(specificationsList);
        }
        if (tbOrdersVO.getIsEvaluate() == 1) {
            SysEvaluate sysEvaluate = sysEvaluateDao.getSysEvaluate(orderId);
            tbOrdersVO.setSysEvaluate(sysEvaluate);
        }
        return Result.success().put("data", tbOrdersVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result appCancelOrder(Long userId, Long orderId) {
        TbOrders tbOrders = baseMapper.selectById(orderId);
        if (tbOrders == null) {
            return Result.error("订单信息不存在");
        }
        if (userId != null) {
            if (!userId.equals(tbOrders.getBuyerId())) {
                return Result.error("您无权操作此订单");
            }
        }
        if (tbOrders.getDeliveryStatus() == 1 || tbOrders.getDeliveryStatus() == 0) {
            if (tbOrders.getStatus() != 0 && tbOrders.getStatus() != 1) {
                return Result.error("订单状态不允许取消");
            }
        }
        if (tbOrders.getIsPay() == 1) {
            if (tbOrders.getPayWay() == 6) {
                // 余额退款
//                userMoneyService.updateMoney(1, tbOrders.getBuyerId(), tbOrders.getOrderMoney().doubleValue());
                UserEntity userEntity = userService.getById(tbOrders.getBuyerId());
                if (userEntity != null) {
                    userEntity.setBalance(userEntity.getBalance().add(tbOrders.getTotalPrice()));
                    userService.updateById(userEntity);
                } else {
                    return Result.error("用户信息不存在，请检查");
                }
            } else if (tbOrders.getPayWay() == 1 || tbOrders.getPayWay() == 2 || tbOrders.getPayWay() == 3 || tbOrders.getPayWay() == 7) {
                // 微信退款
                if (!wxService.refund(tbOrders.getOrderNumber(), null)) {
                    return Result.error("退款异常，请重试");
                }
            } else if (tbOrders.getPayWay() == 4 || tbOrders.getPayWay() == 5) {
                if (!aliPayService.aliRefund(tbOrders.getOrderNumber(), null)) {
                    return Result.error("退款异常，请重试");
                }
            }
            UserEntity userEntity = userService.getById(tbOrders.getSellerId());
            String value = commonInfoService.findOne(79).getValue();
            String value1 = commonInfoService.findOne(87).getValue();
            if ("1".equals(value) || "3".equals(value)) {
                Result result = userService.sendMsg(userEntity.getPhone(), "4");
                if (result.get("code").equals(0) || !result.get("code").equals(0)) {
                    log.warn("发送短信");
                }
            } else {
                Result result = userService.sendMsgAlibabaByValue(userEntity.getPhone(), null, value1);
                if (result.get("code").equals(0) || !result.get("code").equals(0)) {
                    log.warn("发送短信");
                }
            }
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(tbOrders.getBuyerId());
            userMoneyDetails.setTitle("退款成功订单：" + tbOrders.getOrderNumber());
            userMoneyDetails.setContent("退款金额：" + tbOrders.getTotalPrice());
            userMoneyDetails.setType(1);
            userMoneyDetails.setClassify(4);
            userMoneyDetails.setMoney(tbOrders.getTotalPrice());
            userMoneyDetails.setRelationId(orderId);
            userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);
            UserEntity userEntity1 = userService.getById(tbOrders.getBuyerId());
            if (userEntity1 != null) {
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setUserId(String.valueOf(tbOrders.getBuyerId()));
                messageInfo.setTitle("取消订单通知：" + tbOrders.getOrderNumber());
                messageInfo.setContent("您的订单已取消");
                messageInfo.setCreateAt(DateUtils.format(new Date()));
                messageInfo.setIsSee("0");
                messageInfo.setStatus(0);
                messageInfo.setState(String.valueOf(6));
                messageInfo.setUserName(userEntity1.getUserName());
                messageInfoDao.insert(messageInfo);
            }
        }
        // 将优惠券设置为未使用状态
        if (tbOrders.getCouponId() != null) {
            TbCouponUser tbCouponUser = couponUserService.getById(tbOrders.getCouponId());
            if (tbCouponUser != null) {
                tbCouponUser.setStatus(0);
            }
            couponUserService.updateById(tbCouponUser);
        }
        UserEntity userEntity = userDao.selectById(tbOrders.getBuyerId());
        if (userEntity.getOpenId() != null) {
            List<String> msgList = new ArrayList<>();
            msgList.add("您的退款订单：" + tbOrders.getOrderNumber());
            msgList.add("您的退款金额：" + tbOrders.getTotalPrice());
            msgList.add("订单已取消,金额已原路返回,请注意查收！");
//            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//            msgList.add(fmt.format(LocalDateTime.now()));
//            msgList.add("订单已取消,金额已原路返回");
//            msgList.add("您有新的消息，请注意查收");
//            msgList.add(fmt.format(LocalDateTime.now()));
            CommonInfo one = commonInfoService.findOne(236);
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 2);
        }
        tbOrders.setStatus(5);
        tbOrders.setCancelTime(new Date());
        Goods goods = goodsDao.selectById(tbOrders.getGoodId());
//        if (goods != null && goods.getStockId() != null) {
//            goods.setStock(goods.getStock() + tbOrders.getBuyNum());
//            StockManage stockManage = stockManageDao.selectById(goods.getStockId());
//            if (stockManage != null) {
//                stockManage.setOutStock(stockManage.getOutStock() - tbOrders.getBuyNum());
//                stockManageDao.updateById(stockManage);
//            }
//        } else
        if (goods != null && goods.getIsStock() != null && goods.getIsStock() == 2) {
            goods.setStock(goods.getStock() + tbOrders.getBuyNum());
        }
        if (goods != null && goods.getIsEnable() == 0) {
            goods.setStatus(1);
            goods.setIsEnable(1);
        }
        goodsDao.updateById(goods);
        return Result.upStatus(baseMapper.updateById(tbOrders));
    }

    @Override
    public Result appSendGoods(Long userId, Long orderId, String trackingNumber) {
        UserEntity user = userDao.selectById(userId);
        if (user == null) {
            return Result.error("用户信息不存在,请重新登录");
        }
        TbOrders tbOrders = baseMapper.selectById(orderId);
        if (tbOrders != null) {
            if (tbOrders.getStatus() != 1) {
                return Result.error("订单状态不允许发货");
            }
            tbOrders.setStatus(2);
            tbOrders.setSendTime(new Date());
            tbOrders.setTrackingNumber(trackingNumber);
            UserEntity userEntity = userService.queryByUserId(tbOrders.getBuyerId());
            if (userEntity != null) {
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                messageInfo.setTitle("发货订单通知：" + tbOrders.getOrderNumber());
                messageInfo.setContent("您的订单已发货");
                messageInfo.setCreateAt(DateUtils.format(new Date()));
                messageInfo.setIsSee("0");
                messageInfo.setState(String.valueOf(6));
                messageInfo.setUserName(userEntity.getUserName());
                messageInfo.setStatus(0);
                messageInfoDao.insert(messageInfo);
                if (userEntity.getOpenId() != null) {
                    Goods goods = goodsDao.selectById(tbOrders.getGoodId());
                    List<String> msgList = new ArrayList<>();
                    msgList.add("发货通知:" + tbOrders.getOrderNumber());
                    msgList.add("您的商品:" + goods.getGoodTitle() + "已发货,请注意查收");
                    msgList.add("商品数量：" + 1);
                    msgList.add("发货时间：" + tbOrders.getSendTime());
                    msgList.add("发货人：" + user.getUserName());
//                DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//                msgList.add(fmt.format(LocalDateTime.now()));
//                msgList.add("您购买的商品已发货，请注意查收");
//                msgList.add("交易成功,如有问题请联系管理员");
                    CommonInfo one = commonInfoService.findOne(516);
//                msgList.add(fmt.format(LocalDateTime.now()));
                    SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 1);
                }
                if (userEntity.getClientid() != null) {
                    userService.pushToSingle("发货提醒", "您购买的商品已发货，请注意查收", userEntity.getClientid());
                }
            }
            return Result.upStatus(baseMapper.updateById(tbOrders));
        }
        return Result.error("订单信息不存在");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result appReceived(Long userId, Long orderId) {
        UserEntity user = userDao.selectById(userId);
        if (user == null) {
            return Result.error("用户信息不存在,请重新登录");
        }
        TbOrders tbOrders = baseMapper.selectById(orderId);
        if (tbOrders != null) {
            if (tbOrders.getRetrieveType() == 0) {
                if (tbOrders.getStatus() != 8) {
                    return Result.error("订单状态不允许收货");
                }
                tbOrders.setStatus(7);
                tbOrders.setDealTime(new Date());
                UserEntity userEntity = userService.selectUserById(tbOrders.getBuyerId());
                if (userEntity != null) {
                    MessageInfo messageInfo = new MessageInfo();
                    messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                    messageInfo.setTitle("您已成功回收订单，订单号：" + tbOrders.getOrderNumber());
                    messageInfo.setContent("您已成功回收");
                    messageInfo.setCreateAt(DateUtils.format(new Date()));
                    messageInfo.setIsSee("0");
                    messageInfo.setState(String.valueOf(6));
                    messageInfo.setStatus(0);
                    messageInfo.setUserName(userEntity.getUserName());
                    messageInfoDao.insert(messageInfo);
                }
                UserEntity userEntity1 = userService.selectUserById(tbOrders.getSellerId());
                if (userEntity1 != null) {
                    MessageInfo messageInfo = new MessageInfo();
                    messageInfo.setUserId(String.valueOf(userEntity1.getUserId()));
                    messageInfo.setTitle("您的物品已成功回收，订单号：" + tbOrders.getOrderNumber());
                    messageInfo.setContent("您的物品已被回收");
                    messageInfo.setCreateAt(DateUtils.format(new Date()));
                    messageInfo.setIsSee("0");
                    messageInfo.setState(String.valueOf(6));
                    messageInfo.setStatus(0);
                    messageInfo.setUserName(userEntity1.getUserName());
                    messageInfoDao.insert(messageInfo);
                }
                return Result.upStatus(baseMapper.updateById(tbOrders));
            } else {
                if (tbOrders.getStatus() != 2) {
                    return Result.error("订单状态不允许收货");
                }
                UserEntity userEntity = userService.queryByUserId(tbOrders.getSellerId());
                if (userEntity != null) {
                    if (tbOrders.getSellerIncome() == null) {
                        tbOrders.setSellerIncome(BigDecimal.ZERO);
                    }
                    userEntity.setBalance(userEntity.getBalance().add(tbOrders.getSellerIncome()));
                    userService.updateByUserId(userEntity.getUserId(), tbOrders.getSellerIncome().doubleValue());
//                    userMoneyService.updateMoney(1, userEntity.getUserId(), tbOrders.getSellerIncome().doubleValue());
                    UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                    userMoneyDetails.setUserId(tbOrders.getSellerId());
                    userMoneyDetails.setMoney(tbOrders.getSellerIncome());
                    userMoneyDetails.setClassify(1);
//                userMoneyDetails.setUserLevel(2);
                    userMoneyDetails.setRelationId(tbOrders.getOrderId());
                    userMoneyDetails.setType(1);
                    userMoneyDetails.setTitle("收入订单:" + tbOrders.getOrderNumber());
                    userMoneyDetails.setContent("订单号:" + tbOrders.getOrderNumber() + ",订单总价:" + tbOrders.getTotalPrice() + ",本单收入:" + tbOrders.getSellerIncome());
                    userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
                    userMoneyDetailsService.save(userMoneyDetails);
                    if (userEntity.getCreditScore() < 100) {
                        userEntity.setCreditScore(userEntity.getCreditScore() + 1);
                        UserMoneyDetails userMoneyDetails1 = new UserMoneyDetails();
                        userMoneyDetails1.setUserId(tbOrders.getSellerId());
                        userMoneyDetails1.setRelationId(tbOrders.getOrderId());
                        userMoneyDetails1.setType(1);
                        userMoneyDetails1.setClassify(5);
                        userMoneyDetails1.setTitle("订单：" + tbOrders.getOrderNumber());
                        userMoneyDetails1.setContent("用户购买订单，增加信用分：" + 1);
                        userMoneyDetails1.setCreateTime(DateUtils.format(new Date()));
                        userMoneyDetailsService.save(userMoneyDetails1);
                        userService.updateById(userEntity);
                    }
                    setCommission(orderId, 1);
                }
                if (user.getUserId().equals(tbOrders.getBuyerId())) {
                    tbOrders.setStatus(3);
                    tbOrders.setDealTime(new Date());
                    Goods goods = goodsDao.selectById(tbOrders.getGoodId());
                    if (goods != null) {
                        goods.setOutStock(goods.getOutStock() + tbOrders.getBuyNum());
                        goodsDao.updateById(goods);
                    }
                    return Result.upStatus(baseMapper.updateById(tbOrders));
                } else {
                    return Result.error("不是您的订单，请检查后重试");
                }
            }
        }
        return Result.error("订单信息不存在");
    }

    @Override
    public Result appEvaluate(Long userId, Long orderId, String evaluateMessage, Integer satisfactionFlag, String evaluateImg) {
        UserEntity user = userDao.selectById(userId);
        if (user == null) {
            return Result.error("用户信息不存在,请重新登录");
        }
        TbOrders tbOrders = baseMapper.selectById(orderId);
        if (tbOrders != null && tbOrders.getRetrieveType() == 1) {
            if (tbOrders.getStatus() != 3) {
                return Result.error("订单状态不允许评价");
            }
            if (user.getUserId().equals(tbOrders.getBuyerId())) {
                tbOrders.setStatus(4);
                tbOrders.setDealTime(new Date());
                tbOrders.setIsEvaluate(1);
                baseMapper.updateById(tbOrders);
                UserEntity userEntity = userService.queryByUserId(tbOrders.getBuyerId());
                if (userEntity != null) {
                    MessageInfo messageInfo = new MessageInfo();
                    messageInfo.setUserId(String.valueOf(tbOrders.getBuyerId()));
                    messageInfo.setTitle("订单完成通知：" + tbOrders.getOrderNumber());
                    messageInfo.setContent("您的订单已完成");
                    messageInfo.setCreateAt(DateUtils.format(new Date()));
                    messageInfo.setIsSee("0");
                    messageInfo.setState(String.valueOf(6));
                    messageInfo.setStatus(0);
                    messageInfo.setUserName(userEntity.getUserName());
                    messageInfoDao.insert(messageInfo);
                }
                String value = commonInfoService.findOne(294).getValue();
                if ("是".equals(value)) {
                    if (StringUtils.isNotBlank(evaluateMessage)) {
                        if (BaiDuUtils.auditBaiDuText(evaluateMessage)) {
                            return Result.error("您发布的内容包含敏感词汇");
                        }
                    }
                }
                SysEvaluate sysEvaluate = new SysEvaluate();
                // 如果不是回收订单，差评给卖家减信用分
//                UserEntity seller = userDao.selectById(tbOrders.getSellerId());
//                if (seller != null) {
//                    if (seller.getCreditScore() > 0 && seller.getCreditScore() < 100) {
//                        if (satisfactionFlag == 1 || satisfactionFlag == 2) {
//                            seller.setCreditScore(seller.getCreditScore() - 1);
//                            userDao.updateById(seller);
//                            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
//                            userMoneyDetails.setUserId(seller.getUserId());
//                            userMoneyDetails.setTitle("信用分扣除");
//                            userMoneyDetails.setContent("您的订单:" + tbOrders.getOrderNumber() + "被买家评价为差评，扣除信用分");
//                            userMoneyDetails.setType(2);
//                            userMoneyDetails.setMoney(BigDecimal.ZERO);
//                            userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//                            userMoneyDetailsService.save(userMoneyDetails);
//                        }
//                    }
//                }
                sysEvaluate.setIndentNumber(tbOrders.getOrderNumber());
                sysEvaluate.setUserId(user.getUserId());
                sysEvaluate.setRecycleStatus(0);
                sysEvaluate.setEvaluateMessage(evaluateMessage);
                sysEvaluate.setSatisfactionFlag(satisfactionFlag);
                sysEvaluate.setEvaluateImg(evaluateImg);
                sysEvaluate.setFeedbackStatus(0);
                sysEvaluate.setCreateTime(new Date());
                return Result.upStatus(sysEvaluateDao.insert(sysEvaluate));
            }
        } else if (tbOrders != null && tbOrders.getRetrieveType() == 0) {
            if (tbOrders.getStatus() != 7) {
                return Result.error("订单状态不允许评价");
            }
            if (user.getUserId().equals(tbOrders.getSellerId())) {
                tbOrders.setDealTime(new Date());
                tbOrders.setIsEvaluate(1);
                baseMapper.updateById(tbOrders);
//                // 如果是回收订单，差评给买家减信用分
//                UserEntity buyerUser = userDao.selectById(tbOrders.getBuyerId());
//                if (buyerUser != null) {
//                    if (buyerUser.getCreditScore() > 0 && buyerUser.getCreditScore() < 100) {
//                        if (satisfactionFlag == 1 || satisfactionFlag == 2) {
//                            buyerUser.setCreditScore(buyerUser.getCreditScore() - 1);
//                            userDao.updateById(buyerUser);
//                            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
//                            userMoneyDetails.setUserId(buyerUser.getUserId());
//                            userMoneyDetails.setTitle("信用分扣除");
//                            userMoneyDetails.setContent("您的订单:" + tbOrders.getOrderNumber() + "被卖家评价为差评，扣除信用分");
//                            userMoneyDetails.setType(2);
//                            userMoneyDetails.setMoney(BigDecimal.ZERO);
//                            userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//                            userMoneyDetailsService.save(userMoneyDetails);
//                        }
//                    }
//                }
                String value = commonInfoService.findOne(294).getValue();
                if ("是".equals(value)) {
                    if (StringUtils.isNotBlank(evaluateMessage)) {
                        if (BaiDuUtils.auditBaiDuText(evaluateMessage)) {
                            return Result.error("您发布的内容包含敏感词汇");
                        }
                    }
                }
                SysEvaluate sysEvaluate = new SysEvaluate();
                sysEvaluate.setIndentNumber(tbOrders.getOrderNumber());
                sysEvaluate.setUserId(user.getUserId());
                sysEvaluate.setRecycleStatus(1);
                sysEvaluate.setEvaluateMessage(evaluateMessage);
                sysEvaluate.setSatisfactionFlag(satisfactionFlag);
                sysEvaluate.setEvaluateImg(evaluateImg);
                sysEvaluate.setFeedbackStatus(0);
                sysEvaluate.setCreateTime(new Date());
                return Result.upStatus(sysEvaluateDao.insert(sysEvaluate));
            }
        }
        return Result.error("订单信息不存在");
    }

    @Override
    public Result updateEvaluateState(SysEvaluate sysEvaluate) {
        SysEvaluate evaluate = sysEvaluateDao.selectById(sysEvaluate.getEvaluateId());
        if (evaluate != null) {
            evaluate.setFeedbackContent(sysEvaluate.getFeedbackContent());
            evaluate.setFeedbackStatus(sysEvaluate.getFeedbackStatus());
            int result = sysEvaluateDao.updateById(evaluate);
            if (result > 0) {
                if (evaluate.getFeedbackStatus() == 1) {
                    if (evaluate.getSatisfactionFlag() == 1 || evaluate.getSatisfactionFlag() == 2) {
                        TbOrders tbOrders = baseMapper.selectOne(new QueryWrapper<TbOrders>().eq("order_number", evaluate.getIndentNumber()));
                        if (tbOrders != null) {
                            if (tbOrders.getRetrieveType() == 0) {
                                // 如果是回收订单，差评给买家减信用分
                                UserEntity buyerUser = userDao.selectById(tbOrders.getBuyerId());
                                if (buyerUser != null) {
                                    if (buyerUser.getCreditScore() > 0 && buyerUser.getCreditScore() <= 100) {
                                        buyerUser.setCreditScore(buyerUser.getCreditScore() - 1);
                                        userDao.updateById(buyerUser);
                                        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                                        userMoneyDetails.setUserId(buyerUser.getUserId());
                                        userMoneyDetails.setTitle("信用分扣除");
                                        userMoneyDetails.setContent("您的订单:" + tbOrders.getOrderNumber() + "被卖家评价为差评，扣除信用分");
                                        userMoneyDetails.setType(2);
                                        userMoneyDetails.setClassify(5);
                                        userMoneyDetails.setMoney(BigDecimal.ZERO);
                                        userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                        userMoneyDetailsService.save(userMoneyDetails);
                                    }
                                }
                            } else {
                                // 如果不是回收订单，差评给卖家减信用分
                                UserEntity sellerUser = userDao.selectById(tbOrders.getSellerId());
                                if (sellerUser != null) {
                                    if (sellerUser.getCreditScore() > 0 && sellerUser.getCreditScore() <= 100) {
                                        sellerUser.setCreditScore(sellerUser.getCreditScore() - 1);
                                        userDao.updateById(sellerUser);
                                        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                                        userMoneyDetails.setUserId(sellerUser.getUserId());
                                        userMoneyDetails.setTitle("信用分扣除");
                                        userMoneyDetails.setContent("您的订单:" + tbOrders.getOrderNumber() + "被买家评价为差评，扣除信用分");
                                        userMoneyDetails.setType(2);
                                        userMoneyDetails.setClassify(5);
                                        userMoneyDetails.setMoney(BigDecimal.ZERO);
                                        userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                        userMoneyDetailsService.save(userMoneyDetails);
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                return Result.error("评价审核失败");
            }
            return Result.success();
        }
        return Result.error("未找到该条评价，请检查");
    }

    @Override
    public Integer selectOrdersCountStatisticsByYear(Integer flag, String time, Integer status) {
        return baseMapper.selectOrdersCountStatisticsByYear(flag, time, status);
    }

    @Override
    public Result offlineTransaction(TbOrders tbOrders) {
        UserEntity user = userService.getById(tbOrders.getBuyerId());
        if (user == null) {
            return Result.error("该用户未登录，请先登录");
        }
        TbOrders tbspOrders = baseMapper.selectById(tbOrders.getOrderId());
        if (tbspOrders == null) {
            return Result.error("未找到该订单");
        }
        if (tbspOrders.getRetrieveType() == 0) {
            return Result.error("非商品订单，不能进行线下交易");
        }
        baseMapper.updateById(tbOrders);
        return Result.success();
    }

    @Override
    public Result sendGoods(TbOrders tbOrders) {
        TbOrders tbOrders1 = baseMapper.selectById(tbOrders.getOrderId());
        if (tbOrders1 == null) {
            return Result.error("未找到该订单");
        }
        if (tbOrders1.getRetrieveType() == 1) {
            return Result.error("非回收订单，不能发货");
        }
        if (tbOrders1.getStatus() != 6) {
            return Result.error("订单状态异常，请刷新后重试");
        }
        tbOrders.setStatus(8);
        tbOrders.setSendTime(new Date());
        UserEntity userEntity = userService.queryByUserId(tbOrders1.getSellerId());
        if (userEntity != null) {
            if (userEntity.getOpenId() != null) {
                Goods goods = goodsDao.selectById(tbOrders1.getGoodId());
                List<String> msgList = new ArrayList<>();
                msgList.add("发货通知:" + tbOrders.getOrderNumber());
                msgList.add("您的商品:" + goods.getGoodTitle() + "已发货,请注意查收");
                msgList.add("商品数量：" + 1);
                msgList.add("发货时间：" + tbOrders.getSendTime());
                msgList.add("发货人：" + userEntity.getUserName());
                CommonInfo one = commonInfoService.findOne(516);
//                msgList.add(fmt.format(LocalDateTime.now()));
                SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 1);
            }
            if (userEntity.getClientid() != null) {
                userService.pushToSingle("快递提醒", "您回收的物品快递已发，请及时联系", userEntity.getClientid());
            }
        }
        if (baseMapper.updateById(tbOrders) > 0) {
            return Result.success("已成功发货");
        }
        return Result.error("发货失败");
    }

    @Override
    public Result getLogistics(String trackingNumber) {
        String appCode = commonInfoService.findOne(94).getValue();
        String host = "https://wuliu.market.alicloudapi.com";// 【1】请求地址 支持http 和 https 及 WEBSOCKET
        String path = "/kdi";  // 【2】后缀
        String appcode = appCode; // 【3】开通服务后 买家中心-查看AppCode
        String no = trackingNumber.trim();// 【4】请求参数，详见文档描述
        String type = ""; //  【4】请求参数，不知道可不填 95%能自动识别
        String urlSend = host + path + "?no=" + no + "&type=" + type;  // 【5】拼接请求链接
        try {
            URL url = new URL(urlSend);
            HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
            httpURLCon.setRequestProperty("Authorization", "APPCODE " + appcode);// 格式Authorization:APPCODE (中间是英文空格)
            int httpCode = httpURLCon.getResponseCode();
            if (httpCode == 200) {
                String json = read(httpURLCon.getInputStream());
                JSONObject jsonObject = JSONObject.parseObject(json);
                JSONObject phone = jsonObject.getJSONObject("result");
                String phone1 = (String) phone.get("number");
                if (phone1 != null) {
                    java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("^(.*?):");
                    java.util.regex.Matcher matcher = pattern.matcher(phone1);
                    if (matcher.find()) {
                        phone1 = matcher.group(1); // 获取第一个捕获组，即冒号前面的部分
                    }
                    phone.put("number", phone1);
                }
                String statusCode = (String) jsonObject.get("status");
                if (statusCode != null && !statusCode.equals("0")) {
                    return Result.error("物流单号有误请联系发货人");
                }
                return Result.success(jsonObject);
            } else {
                Map<String, List<String>> map = httpURLCon.getHeaderFields();
                String error = map.get("X-Ca-Error-Message").get(0);
                if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
                    System.out.println("AppCode错误 ");
                } else if (httpCode == 400 && error.equals("Invalid Url")) {
                    System.out.println("请求的 Method、Path 或者环境错误");
                } else if (httpCode == 400 && error.equals("Invalid Param Location")) {
                    System.out.println("参数错误");
                } else if (httpCode == 403 && error.equals("Unauthorized")) {
                    System.out.println("服务未被授权（或URL和Path不正确）");
                } else if (httpCode == 403 && error.equals("Quota Exhausted")) {
                    System.out.println("套餐包次数用完 ");
                } else {
                    System.out.println("参数名错误 或 其他错误");
                    System.out.println(error);
                }
            }
        } catch (MalformedURLException e) {
            System.out.println("URL格式错误");
        } catch (UnknownHostException e) {
            System.out.println("URL地址错误");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("查询失败");
    }

    @Override
    public Result updateRecycleOrderByAdmin(TbOrders tbOrders) {
        TbOrders tbOrders1 = baseMapper.selectById(tbOrders.getOrderId());
        if (tbOrders1 == null) {
            return Result.error("未找到该订单");
        }
        if (tbOrders1.getRetrieveType() == 1) {
            return Result.error("非回收订单，不能修改");
        }
        int result = baseMapper.updateById(tbOrders);
        if (result <= 0) {
            return Result.error("修改失败");
        }
        return Result.success();
    }

    @Override
    public Result updateOrderByAdmin(TbOrders tbOrders) {
        TbOrders tbOrders1 = baseMapper.selectById(tbOrders.getOrderId());
        if (tbOrders1 == null) {
            return Result.error("未找到该订单");
        }
        if (tbOrders1.getRetrieveType() == 1) {
            return Result.error("非回收订单，不能修改");
        }
        if (tbOrders1.getStatus() != 6) {
            return Result.error("该回收订单状态异常，暂不能修改");
        }
        int result = baseMapper.updateById(tbOrders);
        if (result <= 0) {
            return Result.error("修改失败");
        }
        return Result.success();
    }

    @Override
    public Result countByRecycleUserId(Long userId) {
        if (userId != null) {
            Integer count = baseMapper.countByRecycleUserId(userId);
            return Result.success().put("data", count);
        }
        return Result.error("该用户不存在");
    }

    @Override
    public Result updateOrderByImg(TbOrders tbOrders) {
        TbOrders tbOrders1 = baseMapper.selectById(tbOrders.getOrderId());
        if (tbOrders.getRecycledImg() != null) {
            UserEntity userEntity = userDao.selectById(tbOrders1.getSellerId());
            if (userEntity != null) {
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
//                if (tbOrders.getRecycledImg() != null) {
//                    messageInfo.setImage(tbOrders.getRecycledImg());
//                }
                messageInfo.setTitle("您的回收订单质检报告已出，请注意查看");
                messageInfo.setContent("回收订单物品质检报告通知");
                messageInfo.setCreateAt(DateUtils.format(new Date()));
                messageInfo.setIsSee("0");
                messageInfo.setState(String.valueOf(6));
                messageInfo.setStatus(0);
                messageInfo.setUserName(userEntity.getUserName());
                messageInfoDao.insert(messageInfo);
                if (userEntity.getOpenId() != null) {
                    List<String> msgList = new ArrayList<>();
                    msgList.add("回收物品质检报告通知：" + tbOrders.getOrderNumber());
                    if (tbOrders.getRecycledImg() != null) {
                        msgList.add("您的回收订单质检报告已出，请查看详情");
                    }
                    CommonInfo one = commonInfoService.findOne(517);
                    SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 3);
                }
                if (userEntity.getClientid() != null) {
                    if (tbOrders.getRecycledImg() != null) {
                        userService.pushToSingle("回收订单通知", "您的回收订单质检报告已出，请注意查收", userEntity.getClientid());
                    }
                }
            }
            tbOrders.setRecycledStatus(1);
            int result = baseMapper.updateById(tbOrders);
            if (result <= 0) {
                return Result.error("修改失败");
            }
            return Result.success();
        }
        return Result.error("上传质检图片为空，请上传质检图片");
    }


    /*
     * 读取返回结果
     */
    private static String read(InputStream is) throws IOException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            line = new String(line.getBytes(), "utf-8");
            sb.append(line);
        }
        br.close();
        return sb.toString();
    }

    @Override
    public IPage<TbOrdersVO> selectTbOrdersList(Integer page, Integer limit, String startTime, String endTime, TbOrdersVO tbOrdersVO) {
        Page<TbOrdersVO> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        IPage<TbOrdersVO> tbOrdersList = baseMapper.getTbOrdersList(pages, startTime, endTime, tbOrdersVO);
        for (TbOrdersVO record : tbOrdersList.getRecords()) {
            if (record.getAddressId() != null) {
                Address address = addressDao.selectById(record.getAddressId());
                if (address != null) {
                    record.setAddressDetail(address.getProvince() + address.getCity() + address.getDistrict() + address.getAddressDetail());
                    record.setBuyerName(address.getUserName());
                    record.setBuyerPhone(address.getUserPhone());
                }
            }
            Goods goods = goodsDao.selectById(record.getGoodId());
            if (goods != null) {
                LabelType labelType = labelTypeDao.selectById(goods.getLabelId());
                if (labelType != null) {
                    record.setLabel(labelType.getLabel());
                }
                GoodsType goodsType = goodsTypeDao.selectById(goods.getTypeId());
                if (goodsType != null) {
                    record.setTypeName(goodsType.getTypeName());
                }
                Brand brand = brandDao.selectById(goods.getBrandId());
                if (brand != null) {
                    record.setBrandId(brand.getId());
                    record.setBrandName(brand.getBrandName());
                    record.setBrandImg(brand.getImg());
                }
                record.setGoods(goods);
                //查询商品规格信息关联信息
                List<GoodsAndSku> goodsAndSkus = goodsAndSkuService.getBaseMapper().selectList(new QueryWrapper<GoodsAndSku>()
                        .eq("goods_id", goods.getGoodId()));
                //解析规格信息
                List<GoodsSpecifications> specificationsList = new ArrayList<>();
                List<String> formNameParts = new ArrayList<>(); // 用于存储规格名称的部分
                if (goodsAndSkus != null && !goodsAndSkus.isEmpty()) {
                    for (GoodsAndSku goodsAndSku : goodsAndSkus) {
                        GoodsSpecifications goodsSpecifications = goodsSpecificationsDao.selectById(goodsAndSku.getSkuId());
                        if (goodsSpecifications != null) {
                            String attributeValues = goodsSpecifications.getAttributeValue();
                            // 使用正则表达式修正字符串中的单引号为双引号
                            attributeValues = attributeValues.replaceAll("'", "\"");
                            // 使用正则表达式将等号替换为冒号
                            attributeValues = attributeValues.replaceAll("(?<=[a-zA-Z0-9_])=", ":");
                            List<AttributeValue> attributeValuesList = JSON.parseArray(attributeValues, AttributeValue.class);
                            goodsSpecifications.setAttributes(attributeValuesList);
                            // 解析 sku_value 字段得到一组 attribute_value 的 ID
                            String[] attributeValueIds = StringUtils.split(goodsAndSku.getSkuValue(), ',');
                            List<AttributeValue> filteredAttributes = new ArrayList<>();
                            for (AttributeValue attribute : goodsSpecifications.getAttributes()) {
                                if (attributeValueIds != null && Arrays.asList(attributeValueIds).contains(String.valueOf(attribute.getId()))) {
                                    attribute.setSpecId(String.valueOf(goodsSpecifications.getId()));
                                    filteredAttributes.add(attribute);
                                    // 收集规格名称到列表中
                                    formNameParts.add(attribute.getAttName());
                                }
                            }
                            goods.setGoodPrice(goods.getGoodPrice());
                            // 设置过滤后的属性值列表
                            goodsSpecifications.setAttributes(filteredAttributes);
                            // 添加到最终的规格列表中
                            specificationsList.add(goodsSpecifications);
                        }
                    }
                    // 使用 join 方法拼接规格名称，确保最后一个元素后不带 '/'
                    String formName = String.join("/", formNameParts);
                    record.setFormName(formName);
//                    // 将规格信息添加到 GoodsVo 中
                    record.setSpecifications(specificationsList);
                }
            }
        }
        return tbOrdersList;
    }

    @Override
    public IPage<TbOrdersVO> selectTbOrdersListByType(Integer page, Integer limit, String startTime, String endTime, TbOrdersVO tbOrdersVO) {
        Page<TbOrdersVO> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        IPage<TbOrdersVO> tbOrdersList = baseMapper.getTbOrdersListByType(pages, startTime, endTime, tbOrdersVO);
        for (TbOrdersVO record : tbOrdersList.getRecords()) {
            Address address = addressDao.selectById(record.getAddressId());
            if (address != null) {
                record.setAddressDetail(address.getProvince() + address.getCity() + address.getDistrict() + address.getAddressDetail());
                record.setSellerName(address.getUserName());
                record.setSellerPhone(address.getUserPhone());
            }
            Goods goods = goodsDao.selectById(record.getGoodId());
            if (goods != null) {
                LabelType labelType = labelTypeDao.selectById(goods.getLabelId());
                if (labelType != null) {
                    record.setLabel(labelType.getLabel());
                }
                Brand brand = brandDao.selectById(goods.getBrandId());
                if (brand != null) {
                    record.setBrandId(brand.getId());
                    record.setBrandName(brand.getBrandName());
                    record.setBrandImg(brand.getImg());
                }
                GoodsRecovery goodsRecovery = goodsRecoveryDao.selectOne(new QueryWrapper<GoodsRecovery>().eq("id", goods.getRecoveryId()));
                record.setRecoveryId(goodsRecovery.getId());
                record.setRecoveryName(goodsRecovery.getName());
                GoodsType goodsType = goodsTypeDao.selectById(goods.getTypeId());
                if (goodsType != null) {
                    record.setTypeName(goodsType.getTypeName());
                }
                //查询商品规格信息关联信息
                List<GoodsAndSku> goodsAndSkus = goodsAndSkuService.getBaseMapper().selectList(new QueryWrapper<GoodsAndSku>()
                        .eq("goods_id", goods.getGoodId()));
                //解析规格信息
                List<GoodsSpecifications> specificationsList = new ArrayList<>();
                List<String> formNameParts = new ArrayList<>(); // 用于存储规格名称的部分
                if (goodsAndSkus != null && !goodsAndSkus.isEmpty()) {
                    for (GoodsAndSku goodsAndSku : goodsAndSkus) {
                        GoodsSpecifications goodsSpecifications = goodsSpecificationsDao.selectById(goodsAndSku.getSkuId());
                        if (goodsSpecifications != null) {
                            String attributeValues = goodsSpecifications.getAttributeValue();
                            // 使用正则表达式修正字符串中的单引号为双引号
                            attributeValues = attributeValues.replaceAll("'", "\"");
                            // 使用正则表达式将等号替换为冒号
                            attributeValues = attributeValues.replaceAll("(?<=[a-zA-Z0-9_])=", ":");
                            List<AttributeValue> attributeValuesList = JSON.parseArray(attributeValues, AttributeValue.class);
                            goodsSpecifications.setAttributes(attributeValuesList);
                            // 解析 sku_value 字段得到一组 attribute_value 的 ID
                            String[] attributeValueIds = StringUtils.split(goodsAndSku.getSkuValue(), ',');
                            List<AttributeValue> filteredAttributes = new ArrayList<>();
                            for (AttributeValue attribute : goodsSpecifications.getAttributes()) {
                                if (attributeValueIds != null && Arrays.asList(attributeValueIds).contains(String.valueOf(attribute.getId()))) {
                                    attribute.setSpecId(String.valueOf(goodsSpecifications.getId()));
                                    filteredAttributes.add(attribute);
                                    // 收集规格名称到列表中
                                    formNameParts.add(attribute.getAttName());
                                }
                            }
                            goods.setGoodPrice(goods.getGoodPrice());
                            // 设置过滤后的属性值列表
                            goodsSpecifications.setAttributes(filteredAttributes);
                            // 添加到最终的规格列表中
                            specificationsList.add(goodsSpecifications);
                        }
                    }
                    // 使用 join 方法拼接规格名称，确保最后一个元素后不带 '/'
                    String formName = String.join("/", formNameParts);
                    record.setFormName(formName);
//                    // 将规格信息添加到 GoodsVo 中
                    record.setSpecifications(specificationsList);
                    record.setGoods(goods);
                }
            }
        }
        return tbOrdersList;
    }

    @Override
    public Result updateOrder(TbOrders tbOrders) {
        TbOrders tbOrders1 = baseMapper.selectById(tbOrders.getOrderId());
        if (tbOrders1.getRetrieveType() == 0 && tbOrders.getStatus() == 5) {
            tbOrders.setCancelTime(new Date());
            UserEntity userEntity = userDao.selectById(tbOrders1.getSellerId());
            if (userEntity != null) {
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                messageInfo.setTitle("您的回收物品订单已被管理取消");
                messageInfo.setContent("您的回收物品已被取消");
                messageInfo.setCreateAt(DateUtils.format(new Date()));
                messageInfo.setIsSee("0");
                messageInfo.setState(String.valueOf(6));
                messageInfo.setStatus(0);
                messageInfo.setUserName(userEntity.getUserName());
                messageInfoDao.insert(messageInfo);
            }
        } else {
            if (tbOrders.getStatus() == 7) {
                tbOrders.setDealTime(new Date());
                UserEntity userEntity = userDao.selectById(tbOrders1.getSellerId());
                if (userEntity != null) {
                    MessageInfo messageInfo = new MessageInfo();
                    messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                    if (tbOrders.getRecycledImg() != null) {
                        messageInfo.setImage(tbOrders.getRecycledImg());
                    }
                    messageInfo.setTitle("您的回收物品订单已完成回收，请注意查看");
                    messageInfo.setContent("回收物品已完成");
                    messageInfo.setCreateAt(DateUtils.format(new Date()));
                    messageInfo.setIsSee("0");
                    messageInfo.setState(String.valueOf(6));
                    messageInfo.setStatus(0);
                    messageInfo.setUserName(userEntity.getUserName());
                    messageInfoDao.insert(messageInfo);
                    if (userEntity.getOpenId() != null) {
                        List<String> msgList = new ArrayList<>();
                        msgList.add("您的回收订单：" + tbOrders.getOrderNumber() + "已完成");
                        if (tbOrders.getRecycledImg() != null) {
                            msgList.add("您的回收订单质检报告已出，请查看详情");
                        } else {
                            msgList.add("回收物品已完成");
                        }
                        CommonInfo one = commonInfoService.findOne(517);
                        SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 3);
                    }
                    if (userEntity.getClientid() != null) {
                        if (tbOrders.getRecycledImg() != null) {
                            userService.pushToSingle("回收订单通知", "您的回收订单质检报告已出，请注意查收", userEntity.getClientid());
                        } else {
                            userService.pushToSingle("回收订单通知", "您的回收订单已完成", userEntity.getClientid());
                        }
                    }
                }
            }
        }
//        int resultCode = goodsService.selectByRecycleGoods(tbOrders1.getGoodId(), tbOrders1.getStatus(), tbOrders1.getTotalPrice());
//        if (resultCode <= 0) {
//            return Result.error("回收商品修改失败，请刷新后充重试");
//        }
        int result = baseMapper.updateById(tbOrders);
        if (result <= 0) {
            return Result.error("回收失败");
        } else {
            return Result.success();
        }
    }

    @Override
    public Result appCancelOrderByType(Long userId, Long orderId) {
        TbOrders tbOrders = baseMapper.selectById(orderId);
        if (tbOrders.getRetrieveType() != 0) {
            UserEntity user = userDao.selectById(tbOrders.getBuyerId());
            if (user.getCreditScore() <= 100 && user.getCreditScore() > 0) {
                user.setCreditScore(user.getCreditScore() - 1);
                userDao.updateById(user);
            }
        }
        if (tbOrders.getStatus() == 6 || tbOrders.getStatus() == 8) {
            tbOrders.setStatus(5);
            tbOrders.setCancelTime(new Date());
            UserEntity userEntity = userService.selectUserById(tbOrders.getBuyerId());
            if (userEntity != null) {
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                messageInfo.setTitle("您已成功取消回收订单，订单号：" + tbOrders.getOrderNumber());
                messageInfo.setContent("您已取消回收订单");
                messageInfo.setCreateAt(DateUtils.format(new Date()));
                messageInfo.setIsSee("0");
                messageInfo.setState(String.valueOf(6));
                messageInfo.setStatus(0);
                messageInfo.setUserName(userEntity.getUserName());
                messageInfoDao.insert(messageInfo);
            }
            UserEntity userEntity1 = userService.selectUserById(tbOrders.getSellerId());
            if (userEntity1 != null) {
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setUserId(String.valueOf(userEntity1.getUserId()));
                messageInfo.setTitle("您的回收订单已取消，订单号：" + tbOrders.getOrderNumber());
                messageInfo.setContent("您的回收订单已被取消");
                messageInfo.setCreateAt(DateUtils.format(new Date()));
                messageInfo.setIsSee("0");
                messageInfo.setStatus(0);
                messageInfo.setState(String.valueOf(6));
                messageInfo.setUserName(userEntity1.getUserName());
                messageInfoDao.insert(messageInfo);
            }
            return Result.upStatus(baseMapper.updateById(tbOrders));
        }
        return Result.error("订单状态不允许取消");
    }

    @Override
    public Result getRecycleAppTbOrdersList(Integer page, Integer limit, TbOrders tbOrders) {
        UserEntity user = userDao.selectById(tbOrders.getBuyerId());
        if (user == null) {
            return Result.error("用户信息不存在,请重新登录");
        }
        Page<TbOrders> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        IPage<TbOrders> ordersVoIPage = baseMapper.getRecycleAppTbOrdersList(pages, tbOrders);
        for (TbOrders record : ordersVoIPage.getRecords()) {
            Goods goods = goodsDao.selectById(record.getGoodId());
            if (goods != null) {
                record.setGoods(goods);
                UserEntity userEntity = userDao.selectById(record.getSellerId());
                record.setSellerPhone(userEntity.getPhone());
                Brand brand = brandDao.selectById(goods.getBrandId());
                if (brand != null) {
                    record.setBrandName(brand.getBrandName());
                    record.setBrandImg(brand.getImg());
                }
                LabelType labelType = labelTypeDao.selectById(goods.getLabelId());
                if (labelType != null) {
                    record.setLabel(labelType.getLabel());
                }
                GoodsRecovery recovery = goodsRecoveryDao.selectById(goods.getRecoveryId());
                if (recovery != null) {
                    record.setRecoveryName(recovery.getName());
                }
            }
            Address address = addressDao.selectById(record.getAddressId());
            if (address != null) {
                record.setAddressDetail(address.getProvince() + address.getCity() + address.getDistrict() + address.getAddressDetail());
            }
            //查询商品规格信息关联信息
            List<GoodsAndSku> goodsAndSkus = goodsAndSkuService.getBaseMapper().selectList(new QueryWrapper<GoodsAndSku>()
                    .eq("goods_id", record.getGoodId()));
            //解析规格信息
            List<GoodsSpecifications> specificationsList = new ArrayList<>();
            if (goodsAndSkus != null) {
                for (GoodsAndSku goodsAndSku : goodsAndSkus) {
                    GoodsSpecifications goodsSpecifications = goodsSpecificationsDao.selectById(goodsAndSku.getSkuId());
                    if (goodsSpecifications != null) {
                        String attributeValues = goodsSpecifications.getAttributeValue();
                        // 使用正则表达式修正字符串中的单引号为双引号
                        attributeValues = attributeValues.replaceAll("'", "\"");
                        // 使用正则表达式将等号替换为冒号
                        attributeValues = attributeValues.replaceAll("(?<=[a-zA-Z0-9_])=", ":");
                        List<AttributeValue> attributeValuesList = JSON.parseArray(attributeValues, AttributeValue.class);
                        goodsSpecifications.setAttributes(attributeValuesList);
                        // 解析 sku_value 字段得到一组 attribute_value 的 ID
                        String[] attributeValueIds = StringUtils.split(goodsAndSku.getSkuValue(), ',');
                        List<AttributeValue> filteredAttributes = new ArrayList<>();
                        for (AttributeValue attribute : goodsSpecifications.getAttributes()) {
                            if (attributeValueIds != null && Arrays.asList(attributeValueIds).contains(String.valueOf(attribute.getId()))) {
                                attribute.setSpecId(String.valueOf(goodsSpecifications.getId()));
                                filteredAttributes.add(attribute);
                            }
                        }
                        if (record.getRetrieveType() == 0) {
                            // 将所有商品规格价格相加，存入这个字段
                            BigDecimal totalPrice = filteredAttributes.stream()
                                    .map(attr -> new BigDecimal(attr.getAttPrice()))
                                    .reduce(BigDecimal.ZERO, BigDecimal::add);
                            tbOrders.setGoodPrice(totalPrice);
                        }
                        // 设置过滤后的属性值列表
                        goodsSpecifications.setAttributes(filteredAttributes);
                        // 添加到最终的规格列表中
                        specificationsList.add(goodsSpecifications);
                    }
                }
                // 将规格信息添加到 GoodsVo 中
                tbOrders.setSpecifications(specificationsList);
            }
        }
        return Result.success().put("data", ordersVoIPage);
    }

    @Override
    public Result assignRecycleUser(Long orderId, Long userId) {
        UserEntity user = userDao.selectById(userId);
        if (user.getRecycleStatus() == 0) {
            return Result.error("当前人员非回收人员，请检查后重试");
        }
        TbOrders tbOrders = baseMapper.selectById(orderId);
        if (tbOrders.getRetrieveType() == 1) {
            return Result.error("当前订单不是回收订单，请检查后重试");
        }
        if (tbOrders.getStatus() == 6 || tbOrders.getStatus() == 8) {
            tbOrders.setBuyerId(userId);
            tbOrders.setStatus(8);
            baseMapper.updateById(tbOrders);
            UserEntity userEntity = userService.selectUserById(tbOrders.getBuyerId());
            if (userEntity != null) {
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                messageInfo.setTitle("您有回收订单待回收，订单号：" + tbOrders.getOrderNumber() + "请及时查看");
                messageInfo.setContent("您有一个待回收的订单");
                messageInfo.setCreateAt(DateUtils.format(new Date()));
                messageInfo.setIsSee("0");
                messageInfo.setStatus(0);
                messageInfo.setState(String.valueOf(6));
                messageInfo.setUserName(userEntity.getUserName());
                messageInfoDao.insert(messageInfo);
            }
            UserEntity userEntity1 = userService.selectUserById(tbOrders.getSellerId());
            if (userEntity1 != null) {
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setUserId(String.valueOf(userEntity1.getUserId()));
                messageInfo.setTitle("您的回收物品已派工作人员前来回收，订单号：" + tbOrders.getOrderNumber() + "请及时联系");
                messageInfo.setContent("您的回收物品已派有工作人员前来回收");
                messageInfo.setCreateAt(DateUtils.format(new Date()));
                messageInfo.setIsSee("0");
                messageInfo.setStatus(0);
                messageInfo.setState(String.valueOf(6));
                messageInfo.setUserName(userEntity1.getUserName());
                messageInfoDao.insert(messageInfo);
            }
            return Result.success("指派成功");
        } else {
            return Result.error("当前订单状态不允许分配回收人员，请刷新后重试");
        }
    }

    @Override
    public Result getEvaluateList(Integer page, Integer limit, SysEvaluate sysEvaluate) {
        Page<SysEvaluate> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        // 普通商品评论
        if (sysEvaluate.getType() == null || sysEvaluate.getType() == 1) {
            IPage<SysEvaluate> evaluateIPage = sysEvaluateDao.selectPageByEvaluateList(pages, sysEvaluate);
            return Result.success().put("data", evaluateIPage);
        } else if (sysEvaluate.getType() == 2) {
            IPage<SysEvaluate> evaluateIPage = sysEvaluateDao.selectEvaluateListByRecycle(pages, sysEvaluate);
            return Result.success().put("data", evaluateIPage);
        } else {
            Page<TrendsComment> pages1;
            if (page != null && limit != null) {
                pages1 = new Page<>(page, limit);
            } else {
                pages1 = new Page<>();
                pages1.setSize(-1);
            }
            IPage<TrendsComment> trendsCommentIPage = trendsCommentDao.selectPageByEvaluateList(pages1, sysEvaluate);
            return Result.success().put("data", trendsCommentIPage);
        }
    }


    @Override
    public Result getTbOrdersList(Integer page, Integer limit, TbOrders tbOrders) {
        Page<TbOrders> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        IPage<TbOrders> ordersVoIPage = baseMapper.getAppTbOrdersBySellerList(pages, tbOrders);
        for (TbOrders record : ordersVoIPage.getRecords()) {
            Goods goods = goodsDao.selectById(record.getGoodId());
//            if (goods != null) {
//                LabelType labelType = labelTypeDao.selectById(goods.getLabelId());
//                if (labelType != null) {
//                    Brand brand = brandDao.selectOne(new QueryWrapper<Brand>().eq("id", goods.getBrandId()));
//                    if (brand != null) {
//                        record.setBrandName(brand.getBrandName());
//                        record.setBrandImg(brand.getImg());
//                    }
//                    GoodsRecovery goodsRecovery = goodsRecoveryDao.selectOne(new QueryWrapper<GoodsRecovery>().eq("id", goods.getRecoveryId()));
//                    if (goodsRecovery != null) {
//                        record.setRecoveryName(goodsRecovery.getName());
//                    }
//                }
//            }
            record.setGoods(goods);
            //查询商品规格信息关联信息
            List<GoodsAndSku> goodsAndSkus = goodsAndSkuService.getBaseMapper().selectList(new QueryWrapper<GoodsAndSku>()
                    .eq("goods_id", record.getGoodId()));
            //解析规格信息
            List<GoodsSpecifications> specificationsList = new ArrayList<>();
            if (goodsAndSkus != null) {
                for (GoodsAndSku goodsAndSku : goodsAndSkus) {
                    GoodsSpecifications goodsSpecifications = goodsSpecificationsDao.selectById(goodsAndSku.getSkuId());
                    if (goodsSpecifications != null) {
                        String attributeValues = goodsSpecifications.getAttributeValue();
                        // 使用正则表达式修正字符串中的单引号为双引号
                        attributeValues = attributeValues.replaceAll("'", "\"");
                        // 使用正则表达式将等号替换为冒号
                        attributeValues = attributeValues.replaceAll("(?<=[a-zA-Z0-9_])=", ":");
                        List<AttributeValue> attributeValuesList = JSON.parseArray(attributeValues, AttributeValue.class);
                        goodsSpecifications.setAttributes(attributeValuesList);
                        // 解析 sku_value 字段得到一组 attribute_value 的 ID
                        String[] attributeValueIds = StringUtils.split(goodsAndSku.getSkuValue(), ',');
                        List<AttributeValue> filteredAttributes = new ArrayList<>();
                        for (AttributeValue attribute : goodsSpecifications.getAttributes()) {
                            if (attributeValueIds != null && Arrays.asList(attributeValueIds).contains(String.valueOf(attribute.getId()))) {
                                attribute.setSpecId(String.valueOf(goodsSpecifications.getId()));
                                filteredAttributes.add(attribute);
                            }
                        }
                        if (record.getRetrieveType() == 0) {
                            // 将所有商品规格价格相加，存入这个字段
                            BigDecimal totalPrice = filteredAttributes.stream()
                                    .map(attr -> new BigDecimal(attr.getAttPrice()))
                                    .reduce(BigDecimal.ZERO, BigDecimal::add);
                            tbOrders.setGoodPrice(totalPrice);
                        }
                        // 设置过滤后的属性值列表
                        goodsSpecifications.setAttributes(filteredAttributes);
                        // 添加到最终的规格列表中
                        specificationsList.add(goodsSpecifications);
                    }
                }
                // 将规格信息添加到 GoodsVo 中
                record.setSpecifications(specificationsList);
            }
        }
        return Result.success().put("data", ordersVoIPage);
    }

    @Override
    public Result getTbOrdersListByTurnover(Long userId, Integer page, Integer limit) {
        Page<SysEvaluate> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        List<SysEvaluate> sysEvaluateList = sysEvaluateDao.getTbOrdersListByTurnover(pages);
        Integer total = baseMapper.selectCount(new QueryWrapper<TbOrders>().eq("retrieve_type", 0).and(w -> w.eq("status", 7)));
        Map<String, Object> map = new HashMap<>();
        // 评论列表
        map.put("data", sysEvaluateList);
        // 最近成交数
        map.put("total", total);
        return Result.success(map);
    }

    @Override
    public void payBack(String outTradeNo) {
        TbOrders tbOrders = baseMapper.selectOne(new QueryWrapper<TbOrders>().eq("order_number", outTradeNo));
        if (tbOrders != null) {
            PayDetails payDetails = payDetailsDao.selectByOrderId(outTradeNo);
            if (payDetails != null) {
                tbOrders.setPayWay(payDetails.getClassify());
            }
            if (tbOrders.getRetrieveType() == 0) {
                tbOrders.setStatus(7);
                UserEntity user = userDao.selectById(tbOrders.getSellerId());
                UserEntity buyer = userDao.selectById(tbOrders.getBuyerId());
                if (StringUtils.isNotBlank(user.getOpenId())) {
                    Goods goods = goodsDao.selectById(tbOrders.getGoodId());
                    List<String> msgList = new ArrayList<>();
                    msgList.add("回收订单:" + tbOrders.getOrderNumber() + "已下单成功");
                    msgList.add("您的商品:" + goods.getGoodTitle() + "已支付成功");
                    msgList.add("商品数量：" + 1);
                    msgList.add("支付时间：" + new Date());
                    msgList.add("购买方：" + buyer.getUserName());
//                    msgList.add("订单通知");
//                    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//                    msgList.add(fmt.format(LocalDateTime.now()));
//                    msgList.add("您的回收订单已交易成功，请注意查看");
//                    msgList.add("交易成功,如有问题请联系管理员");
                    CommonInfo one = commonInfoService.findOne(516);
//                    msgList.add(fmt.format(LocalDateTime.now()));
                    SenInfoCheckUtil.sendMsg(user.getOpenId(), one.getValue(), msgList, 1);
                }
                if (user.getClientid() != null) {
                    userService.pushToSingle("回收订单", "您的回收订单已交易成功，请注意查看", user.getClientid());
                }
                UserEntity userByWxId = userDao.selectById(tbOrders.getBuyerId());
                if (StringUtils.isNotBlank(userByWxId.getOpenId())) {
                    Goods goods = goodsDao.selectById(tbOrders.getGoodId());
                    List<String> msgList = new ArrayList<>();
                    msgList.add("您的回收订单:" + tbOrders.getOrderNumber() + "已下单成功");
                    msgList.add("您购买的商品:" + goods.getGoodTitle() + "已支付成功");
                    msgList.add("商品数量：" + 1);
                    msgList.add("支付时间：" + new Date());
                    msgList.add("购买方：" + buyer.getUserName());
                    CommonInfo one = commonInfoService.findOne(516);
//                    msgList.add(fmt.format(LocalDateTime.now()));
                    SenInfoCheckUtil.sendMsg(user.getOpenId(), one.getValue(), msgList, 1);
                }
                if (userByWxId.getClientid() != null) {
                    userService.pushToSingle("回收订单", "您已成功购买回收订单，请注意查看", userByWxId.getClientid());
                }
            } else if (tbOrders.getRetrieveType() == 1 && tbOrders.getDeliveryStatus() == 2) {
                if ((tbOrders.getStatus() == 1 || tbOrders.getStatus() == 2 || tbOrders.getStatus() == 3 || tbOrders.getStatus() == 4 || tbOrders.getStatus() == 5) && tbOrders.getIsPay() == 1) {
                    tbOrders.setStatus(tbOrders.getStatus());
                    baseMapper.updateById(tbOrders);
                } else {
                    UserEntity user = userDao.selectById(tbOrders.getSellerId());
                    UserEntity buyer = userDao.selectById(tbOrders.getBuyerId());
                    String value = commonInfoService.findOne(79).getValue();
                    String value1 = commonInfoService.findOne(86).getValue();
                    if ("1".equals(value) || "3".equals(value)) {
                        Result result = userService.sendMsg(user.getPhone(), "2");
                        if (result.get("code").equals(0) || !result.get("code").equals(0)) {
                            log.warn("发送短信");
                        }
                    } else {
                        Result result = userService.sendMsgAlibabaByValue(user.getPhone(), null, value1);
                        if (result.get("code").equals(0) || !result.get("code").equals(0)) {
                            log.warn("发送短信");
                        }
                    }
                    MessageInfo messageInfo = new MessageInfo();
                    messageInfo.setUserId(String.valueOf(buyer.getUserId()));
                    messageInfo.setTitle("下单成功通知，订单号：" + tbOrders.getOrderNumber());
                    messageInfo.setContent("您已下单成功");
                    messageInfo.setCreateAt(DateUtils.format(new Date()));
                    messageInfo.setIsSee("0");
                    messageInfo.setStatus(0);
                    messageInfo.setState(String.valueOf(6));
                    messageInfo.setUserName(buyer.getUserName());
                    messageInfoDao.insert(messageInfo);

                    MessageInfo messageInfos = new MessageInfo();
                    messageInfos.setUserId(String.valueOf(user.getUserId()));
                    messageInfos.setTitle("您的商品已被成功购买通知，订单号：" + tbOrders.getOrderNumber());
                    messageInfos.setContent("您商品已被成功购买");
                    messageInfos.setCreateAt(DateUtils.format(new Date()));
                    messageInfos.setIsSee("0");
                    messageInfos.setStatus(0);
                    messageInfos.setState(String.valueOf(6));
                    messageInfos.setUserName(user.getUserName());
                    messageInfoDao.insert(messageInfos);

                    if (StringUtils.isNotBlank(user.getOpenId())) {
                        Goods goods = goodsDao.selectById(tbOrders.getGoodId());
                        List<String> msgList = new ArrayList<>();
                        msgList.add("商品订单:" + tbOrders.getOrderNumber());
                        msgList.add("您的商品:" + goods.getGoodTitle() + "已支付成功");
                        msgList.add("商品数量：" + 1);
                        msgList.add("支付时间：" + new Date());
                        msgList.add("购买方：" + buyer.getUserName());
                        CommonInfo one = commonInfoService.findOne(516);
//                        msgList.add(fmt.format(LocalDateTime.now()));
                        SenInfoCheckUtil.sendMsg(user.getOpenId(), one.getValue(), msgList, 1);
                    }
                    if (user.getClientid() != null) {
                        userService.pushToSingle("商品订单", "您的商品订单已下单成功，请留意消息！", user.getClientid());
                    }
                    UserEntity userByWxId = userDao.selectById(tbOrders.getBuyerId());
                    if (StringUtils.isNotBlank(userByWxId.getOpenId())) {
                        Goods goods = goodsDao.selectById(tbOrders.getGoodId());
                        List<String> msgList = new ArrayList<>();
                        msgList.add("您的商品订单:" + tbOrders.getOrderNumber() + "已下单成功");
                        msgList.add("您的商品:" + goods.getGoodTitle() + "已支付成功");
                        msgList.add("商品数量：" + 1);
                        msgList.add("支付时间：" + new Date());
                        msgList.add("购买方：" + userByWxId.getUserName());
                        CommonInfo one = commonInfoService.findOne(516);
//                        msgList.add(fmt.format(LocalDateTime.now()));
                        SenInfoCheckUtil.sendMsg(user.getOpenId(), one.getValue(), msgList, 1);
                    }
                    if (userByWxId.getClientid() != null) {
                        userService.pushToSingle("商品订单", "您已成功购买商品订单，请注意查看", userByWxId.getClientid());
                    }
                    tbOrders.setStatus(2);
                    tbOrders.setIsPay(1);
                    tbOrders.setPayTime(new Date());
                    String platformIncome = commonInfoService.findOne(448).getValue();
                    BigDecimal plateBalance = new BigDecimal(platformIncome);
                    tbOrders.setPlatformIncome(tbOrders.getTotalPrice().multiply(plateBalance));
                    tbOrders.setSellerIncome(tbOrders.getTotalPrice().subtract(tbOrders.getPlatformIncome()));
                    int result = baseMapper.updateById(tbOrders);
                    UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                    userMoneyDetails.setUserId(tbOrders.getBuyerId());
                    userMoneyDetails.setMoney(tbOrders.getTotalPrice());
                    if (payDetails.getClassify() == 1 || payDetails.getClassify() == 2 || payDetails.getClassify() == 3) {
                        userMoneyDetails.setContent("微信支付：" + tbOrders.getTotalPrice());
                        userMoneyDetails.setTitle("支付成功");
                        userMoneyDetails.setType(2);
                        userMoneyDetails.setClassify(1);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String format = simpleDateFormat.format(new Date());
                        userMoneyDetails.setCreateTime(format);
                        userMoneyDetailsService.save(userMoneyDetails);
                    } else {
                        userMoneyDetails.setContent("支付宝支付：" + tbOrders.getTotalPrice());
                        userMoneyDetails.setTitle("支付成功");
                        userMoneyDetails.setType(2);
                        userMoneyDetails.setClassify(1);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String format = simpleDateFormat.format(new Date());
                        userMoneyDetails.setCreateTime(format);
                        userMoneyDetailsService.save(userMoneyDetails);
                    }
                    if (result > 0) {
                        Goods goods = goodsDao.selectOne(new QueryWrapper<Goods>().eq("good_id", tbOrders.getGoodId()));
                        if (goods != null) {
                            if (goods.getStockId() != null) {
                                StockManage stockManage = stockManageDao.selectById(goods.getStockId());
                                if (stockManage != null) {
                                    stockManage.setOutStock(stockManage.getOutStock() + tbOrders.getBuyNum());
                                    stockManage.setOutPrice(goods.getGoodPrice());
                                    stockManageDao.updateById(stockManage);
                                    if (goods.getStock() == 0) {
                                        goods.setStatus(1);
                                        goods.setIsEnable(0);
                                        goodsDao.updateById(goods);
                                    }
                                }
                            } else {
                                goods.setStatus(1);
                                goods.setIsEnable(0);
                                goodsDao.updateById(goods);
                            }
                        }
                    }
                }
            } else if (tbOrders.getRetrieveType() == 1) {
                if ((tbOrders.getStatus() == 1 || tbOrders.getStatus() == 2 || tbOrders.getStatus() == 3 || tbOrders.getStatus() == 4 || tbOrders.getStatus() == 5) && tbOrders.getIsPay() == 1) {
                    tbOrders.setStatus(tbOrders.getStatus());
                    baseMapper.updateById(tbOrders);
                } else {
                    UserEntity user = userDao.selectById(tbOrders.getBuyerId());
                    if (StringUtils.isNotBlank(user.getOpenId())) {
                        Goods goods = goodsDao.selectById(tbOrders.getGoodId());
                        List<String> msgList = new ArrayList<>();
                        msgList.add("您的订单:" + tbOrders.getOrderNumber() + "已下单成功");
                        msgList.add("您的商品:" + goods.getGoodTitle() + "已支付成功");
                        msgList.add("商品数量：" + 1);
                        msgList.add("支付时间：" + new Date());
                        msgList.add("购买方：" + user.getUserName());
                        CommonInfo one = commonInfoService.findOne(516);
//                        msgList.add(fmt.format(LocalDateTime.now()));
                        SenInfoCheckUtil.sendMsg(user.getOpenId(), one.getValue(), msgList, 1);
                    }
                    if (user.getClientid() != null) {
                        userService.pushToSingle("商品订单", "您的商品订单已下单成功，请留意消息！", user.getClientid());
                    }
                    UserEntity userByWxId = userDao.selectById(tbOrders.getSellerId());
                    String value = commonInfoService.findOne(79).getValue();
                    String value1 = commonInfoService.findOne(86).getValue();
                    if ("1".equals(value) || "3".equals(value)) {
                        Result result = userService.sendMsg(userByWxId.getPhone(), "2");
                        if (result.get("code").equals(0) || !result.get("code").equals(0)) {
                            log.warn("发送短信");
                        }
                    } else {
                        Result result = userService.sendMsgAlibabaByValue(userByWxId.getPhone(), null, value1);
                        if (result.get("code").equals(0) || !result.get("code").equals(0)) {
                            log.warn("发送短信");
                        }
                    }
                    if (StringUtils.isNotBlank(userByWxId.getOpenId())) {
                        Goods goods = goodsDao.selectById(tbOrders.getGoodId());
                        List<String> msgList = new ArrayList<>();
                        msgList.add("您的订单:" + tbOrders.getOrderNumber());
                        msgList.add("您的商品:" + goods.getGoodTitle() + "已支付成功");
                        msgList.add("商品数量：" + 1);
                        msgList.add("支付时间：" + new Date());
                        msgList.add("购买方：" + user.getUserName());
                        CommonInfo one = commonInfoService.findOne(516);
//                        msgList.add(fmt.format(LocalDateTime.now()));
                        SenInfoCheckUtil.sendMsg(userByWxId.getOpenId(), one.getValue(), msgList, 1);
                    }
                    if (userByWxId.getClientid() != null) {
                        userService.pushToSingle("商品订单", "您的商品已被购买，请注意查看", userByWxId.getClientid());
                    }
                    MessageInfo messageInfo = new MessageInfo();
                    messageInfo.setUserId(String.valueOf(user.getUserId()));
                    messageInfo.setTitle("下单成功通知，订单号：" + tbOrders.getOrderNumber());
                    messageInfo.setContent("您已下单成功");
                    messageInfo.setCreateAt(DateUtils.format(new Date()));
                    messageInfo.setIsSee("0");
                    messageInfo.setStatus(0);
                    messageInfo.setState(String.valueOf(6));
                    messageInfo.setUserName(user.getUserName());
                    messageInfoDao.insert(messageInfo);

                    MessageInfo messageInfos = new MessageInfo();
                    messageInfos.setUserId(String.valueOf(userByWxId.getUserId()));
                    messageInfos.setTitle("您的商品已被成功购买通知，订单号：" + tbOrders.getOrderNumber());
                    messageInfos.setContent("您商品已被成功购买");
                    messageInfos.setCreateAt(DateUtils.format(new Date()));
                    messageInfos.setIsSee("0");
                    messageInfos.setStatus(0);
                    messageInfos.setState(String.valueOf(6));
                    messageInfos.setUserName(userByWxId.getUserName());
                    messageInfoDao.insert(messageInfos);
                    tbOrders.setStatus(1);
                    tbOrders.setIsPay(1);
                    tbOrders.setPayTime(new Date());
                    String platformIncome = commonInfoService.findOne(448).getValue();
                    BigDecimal plateBalance = new BigDecimal(platformIncome);
                    tbOrders.setPlatformIncome(tbOrders.getTotalPrice().multiply(plateBalance));
                    tbOrders.setSellerIncome(tbOrders.getTotalPrice().subtract(tbOrders.getPlatformIncome()));
                    int result = baseMapper.updateById(tbOrders);
                    UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                    userMoneyDetails.setUserId(tbOrders.getBuyerId());
                    userMoneyDetails.setMoney(tbOrders.getTotalPrice());
                    if (payDetails.getClassify() == 1 || payDetails.getClassify() == 2 || payDetails.getClassify() == 3) {
                        userMoneyDetails.setContent("微信支付：" + tbOrders.getTotalPrice());
                        userMoneyDetails.setTitle("支付成功");
                        userMoneyDetails.setType(2);
                        userMoneyDetails.setClassify(1);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String format = simpleDateFormat.format(new Date());
                        userMoneyDetails.setCreateTime(format);
                        userMoneyDetailsService.save(userMoneyDetails);
                    } else {
                        userMoneyDetails.setContent("支付宝支付：" + tbOrders.getTotalPrice());
                        userMoneyDetails.setTitle("支付成功");
                        userMoneyDetails.setType(2);
                        userMoneyDetails.setClassify(1);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String format = simpleDateFormat.format(new Date());
                        userMoneyDetails.setCreateTime(format);
                        userMoneyDetailsService.save(userMoneyDetails);
                    }
                    if (result > 0) {
                        Goods goods = goodsDao.selectOne(new QueryWrapper<Goods>().eq("good_id", tbOrders.getGoodId()));
                        if (goods != null && goods.getStockId() != null) {
                            StockManage stockManage = stockManageDao.selectById(goods.getStockId());
                            if (stockManage != null) {
                                stockManage.setOutStock(stockManage.getOutStock() + tbOrders.getBuyNum());
                                stockManage.setOutPrice(goods.getGoodPrice());
                                stockManageDao.updateById(stockManage);
                                if (goods.getStock() == 0) {
                                    goods.setStatus(1);
                                    goods.setIsEnable(0);
                                    goodsDao.updateById(goods);
                                }
                            }
                        } else if (goods != null && goods.getIsStock() != null) {
                            if (goods.getIsStock() == 2 && goods.getStock() == 0) {
                                goods.setStatus(1);
                                goods.setIsEnable(0);
                                goodsDao.updateById(goods);
                            } else if (goods.getIsStock() == 2 && goods.getStock() > 0) {
                                goods.setStatus(1);
                                goods.setIsEnable(1);
                                goods.setStock(goods.getStock() - tbOrders.getBuyNum());
                                goodsDao.updateById(goods);
                            } else if (goods.getIsStock() == 1) {
                                goods.setStatus(1);
                                goods.setIsEnable(0);
                                goodsDao.updateById(goods);
                            }
                        } else if (goods != null) {
                            goods.setStatus(1);
                            goods.setIsEnable(0);
                            goodsDao.updateById(goods);
                        }
                    }
                }
            }
        }
    }

    /**
     * 计算用户上级收益
     *
     * @param orderId  此真实为订单号
     * @param classify 1订单分成 2订单退款
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setCommission(Long orderId, int classify) {
        //计算用户上级收益
        // 是否开启固定金额分成
        String value = commonInfoService.findOne(812).getValue();
        // 一级固定分成金额
        String firstCommission = commonInfoService.findOne(813).getValue();
        // 二级固定分成金额
        String secondCommission = commonInfoService.findOne(814).getValue();
        TbOrders tbOrders = baseMapper.selectOne(new QueryWrapper<TbOrders>().eq("order_id", orderId));
        UserEntity user = userService.queryByUserId(tbOrders.getBuyerId());
        BigDecimal amount = BigDecimal.ZERO;
        if (tbOrders.getFirstCommission() == null) {
            tbOrders.setFirstCommission(BigDecimal.ZERO);
        }
        if (tbOrders.getSecondCommission() == null) {
            tbOrders.setSecondCommission(BigDecimal.ZERO);
        }
        if (user != null) {
            if ("是".equals(value)) {
                // 查他的上级
                UserEntity userParent = userService.getOne(new QueryWrapper<UserEntity>().eq("invitation_code", user.getInviterCode()));
                if (userParent != null) {
                    if (userParent.getDivideScale() != null) {
                        // 使用BigDecimal来处理分佣比例，确保精确度
                        BigDecimal divideScale = new BigDecimal(userParent.getDivideScale());
                        // 获取一级固定分佣金额，如果一级分佣比例大于0，则给一级分佣
                        if ((divideScale.compareTo(BigDecimal.ZERO) > 0)) {
                            BigDecimal money = new BigDecimal(firstCommission);
                            tbOrders.setFirstCommission(new BigDecimal(firstCommission));
                            tbOrders.setFirstUserId(userParent.getUserId());
                            this.setIndentMoneyDetails(user, userParent, tbOrders, money, 1, classify);
                        }
                    }
                    // 查他的上上级
                    UserEntity userParentTwo = userService.getOne(new QueryWrapper<UserEntity>().eq("invitation_code", userParent.getInviterCode()));
                    if (userParentTwo != null) {
                        // 使用BigDecimal来处理分佣比例，确保精确度
                        if (userParentTwo.getDivideTwoScale() != null) {
                            BigDecimal divideTwoScale = new BigDecimal(userParentTwo.getDivideTwoScale());
                            // 获取二级固定分佣金额，如果二级分佣比例大于0，则给二级分佣
                            if ((divideTwoScale.compareTo(BigDecimal.ZERO) > 0)) {
                                BigDecimal moneyTwo = new BigDecimal(secondCommission);
                                tbOrders.setSecondCommission(moneyTwo);
                                tbOrders.setSecondUserId(userParentTwo.getUserId());
                                this.setIndentMoneyDetails(user, userParentTwo, tbOrders, moneyTwo, 2, classify);
                            }
                        }
                    }
                }
            } else {
                // 查他的上级
                UserEntity userParent = userService.getOne(new QueryWrapper<UserEntity>().eq("invitation_code", user.getInviterCode()));
                if (userParent != null) {
                    if (user.getDivideScale() != null) {
                        // 获取一级分佣比例，如果一级分佣比例大于0，则给一级分佣
                        BigDecimal divideScale = new BigDecimal(user.getDivideScale());
                        if ((divideScale.compareTo(BigDecimal.ZERO) > 0)) {
                            BigDecimal money = tbOrders.getPlatformIncome().multiply(divideScale);
                            amount = money;
                            tbOrders.setFirstCommission(money);
                            tbOrders.setFirstUserId(userParent.getUserId());
                            this.setIndentMoneyDetails(user, userParent, tbOrders, money, 1, classify);
                        }
                    }
//                    String divideScale = userParent.getDivideScale();
//                    BigDecimal money = tbOrders.getPlatformIncome().multiply(new BigDecimal(divideScale));
//                    amount = money;
//                    tbOrders.setFirstCommission(money);
//                    tbOrders.setFirstUserId(userParent.getUserId());
//                    this.setIndentMoneyDetails(user, userParent, tbOrders, money, 1, classify);
                    // 查他的上上级
                    UserEntity userParentTwo = userService.getOne(new QueryWrapper<UserEntity>().eq("invitation_code", userParent.getInviterCode()));
                    if (userParentTwo != null) {
                        if (userParentTwo.getDivideTwoScale() != null) {
                            // 获取二级分佣比例，如果二级分佣比例大于0，则给二级分佣
                            BigDecimal divideTwoScale = new BigDecimal(userParentTwo.getDivideTwoScale());
                            if ((divideTwoScale.compareTo(BigDecimal.ZERO) > 0)) {
                                BigDecimal moneyTwo = tbOrders.getPlatformIncome().multiply(divideTwoScale);
                                amount = amount.add(moneyTwo);
                                tbOrders.setSecondCommission(moneyTwo);
                                tbOrders.setSecondUserId(userParentTwo.getUserId());
                                this.setIndentMoneyDetails(user, userParentTwo, tbOrders, moneyTwo, 2, classify);
                            }
//                            String divideTwoScale = userParentTwo.getDivideTwoScale();
//                            BigDecimal moneyTwo = tbOrders.getPlatformIncome().multiply(new BigDecimal(divideTwoScale));
//                            amount = amount.add(moneyTwo);
//                            tbOrders.setSecondCommission(moneyTwo);
//                            tbOrders.setSecondUserId(userParentTwo.getUserId());
//                            this.setIndentMoneyDetails(user, userParentTwo, tbOrders, moneyTwo, 2, classify);
                        }
                    }
                }
            }
            tbOrders.setPlatformIncome(tbOrders.getPlatformIncome().subtract(amount));
            baseMapper.updateById(tbOrders);
        }
    }

    @Override
    public Result updateRecycleOrder(TbOrders tbOrders) {
        TbOrders tbOrders1 = baseMapper.selectOne(new QueryWrapper<TbOrders>().eq("order_id", tbOrders.getOrderId()));
        if (tbOrders1 != null && tbOrders1.getRetrieveType() == 1) {
            return Result.error("该订单不是回收订单，请检查");
        }
        if (tbOrders1 != null && (tbOrders1.getStatus() == 6 || tbOrders1.getStatus() == 8)) {
            baseMapper.updateById(tbOrders);
            return Result.success();
        } else {
            return Result.error("订单状态已变更，请刷新后重试");
        }
    }


    /**
     * @param userEntity 用户id
     * @param tbOrders   订单
     * @param type       1一级用户 2二级用户
     * @param classify   1订单分成 2订单退款
     */
    private void setIndentMoneyDetails(UserEntity userEntity1, UserEntity userEntity, TbOrders tbOrders, BigDecimal money, int type,
                                       int classify) {
        String title;
        //增加余额
        BigDecimal moneyDetails;
        if (classify == 1) {
            moneyDetails = userEntity.getBalance().add(money);
            title = "分成";
        } else {
            moneyDetails = userEntity.getBalance().subtract(money);
            title = "退款";
        }
        userDao.updateRiderBalance(money, userEntity.getUserId());
        //添加用户邀请人钱包详情
        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
        if (type == 1) {
            userMoneyDetails.setMoney(money);
            userMoneyDetails.setUserLevel(1);
            userMoneyDetails.setRelationId(userEntity1.getUserId());
            userMoneyDetails.setUserId(userEntity.getUserId());
            userMoneyDetails.setType(1);
            userMoneyDetails.setClassify(classify);
            userMoneyDetails.setTitle("一级用户订单:" + tbOrders.getOrderNumber());
            userMoneyDetails.setContent("订单号:" + tbOrders.getOrderNumber() + ",订单总价:" + tbOrders.getTotalPrice() + "," + title + "金额:" + money);
            userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);
//            userService.updateByUserId(userEntity.getUserId(), money.doubleValue());
//            userMoneyService.updateMoney(1, userEntity.getUserId(), money.doubleValue());
        } else if (type == 2) {
            userMoneyDetails.setMoney(money);
            userMoneyDetails.setRelationId(userEntity1.getUserId());
            userMoneyDetails.setUserId(userEntity.getUserId());
            userMoneyDetails.setUserLevel(2);
            userMoneyDetails.setType(1);
            userMoneyDetails.setClassify(classify);
            userMoneyDetails.setTitle("二级用户订单:" + tbOrders.getOrderNumber());
            userMoneyDetails.setContent("订单号:" + tbOrders.getOrderNumber() + ",订单总价:" + tbOrders.getTotalPrice() + "," + title + "金额:" + money);
            userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);
//            userService.updateByUserId(userEntity.getUserId(), money.doubleValue());
//            userMoneyService.updateMoney(1, userEntity.getUserId(), money.doubleValue());
        }
        if (userEntity.getClientid() != null) {
            //app端用户消息推送
            userService.pushToSingle("订单分成", "订单号:" + tbOrders.getOrderNumber() + ",订单总价:" + tbOrders.getTotalPrice() + "," + title + "金额:" + money, userEntity.getClientid());
        }
    }
}




